package com.boot.security.server.authentication.mobile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 短信验证登录逻辑
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //传进来的authentication就是我们自定义的SmsCodeAuthenticationToken，强转
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken)authentication;
        //Principal就是手机号码,根据手机号码获取用户信息
        UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());

        if (user == null){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }

        //生成已认证Token
        SmsCodeAuthenticationToken smsCodeAuthenticationResult = new SmsCodeAuthenticationToken(user,user.getAuthorities());
        //吧authenticationToken中未认证的Details放到smsCodeAuthenticationResult的Details中认证
        smsCodeAuthenticationResult.setDetails(authenticationToken.getDetails());

        return smsCodeAuthenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
